﻿using Furion.DatabaseAccessor;
using Furion.DatabaseAccessor.Extensions;
using Furion.DependencyInjection;
using Furion.DynamicApiController;
using Furion.FriendlyException;
using Admin.NET.Core;
using Mapster;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System.Linq.Dynamic.Core;
using Microsoft.AspNetCore.Http;
using System.Text;
using System.Web;

namespace Admin.NET.Application
{
    /// <summary>
    /// PDA菜单服务
    /// </summary>
    [ApiDescriptionSettings("自己的业务", Name = "WmsPdaPower", Order = 100)]
    [Route("api/[Controller]")]
    public class WmsPdaPowerService : IWmsPdaPowerService, IDynamicApiController, ITransient
    {
        private readonly IRepository<WmsPdaPower,MasterDbContextLocator> _wmsPdaPowerRep;
        private readonly IRepository<SysDictType, MasterDbContextLocator> _sysDictTypeRep;
        private readonly IRepository<SysDictData, MasterDbContextLocator> _sysDictDataRep;
        private readonly ISysExcelTemplateService _sysExcelTemplateService;
        private readonly static object _lock = new();

        public WmsPdaPowerService(
            IRepository<WmsPdaPower,MasterDbContextLocator> wmsPdaPowerRep
            ,IRepository<SysDictType, MasterDbContextLocator> sysDictTypeRep
            ,IRepository<SysDictData, MasterDbContextLocator> sysDictDataRep
            ,ISysExcelTemplateService sysExcelTemplateService
        )
        {
             _wmsPdaPowerRep = wmsPdaPowerRep;
             _sysDictTypeRep = sysDictTypeRep;
             _sysDictDataRep = sysDictDataRep;
             _sysExcelTemplateService = sysExcelTemplateService;
        }

        /// <summary>
        /// 构造函数
        /// </summary>
        [HttpGet("page")]
        public async Task<PageResult<WmsPdaPowerOutput>> Page([FromQuery] WmsPdaPowerSearch input)
        {
            var wmsPdaPowers = await _wmsPdaPowerRep.DetachedEntities
                                     .Where(!string.IsNullOrEmpty(input.Code), u => EF.Functions.Like(u.Code, $"%{input.Code.Trim()}%"))
                                     .Where(!string.IsNullOrEmpty(input.Name), u => EF.Functions.Like(u.Name, $"%{input.Name.Trim()}%"))
                                     .Where(input.WorkShopType != null, u => u.WorkShopType == input.WorkShopType)
                                     .OrderBy(PageInputOrder.OrderBuilder<WmsPdaPowerSearch>(input))
                                     .ProjectToType<WmsPdaPowerOutput>()
                                     .ToADPagedListAsync(input.PageNo, input.PageSize);
            return wmsPdaPowers;
        }

        /// <summary>
        /// 不分页查询PDA菜单列表
        /// </summary>
        /// <param name="input">PDA菜单查询参数</param>
        /// <returns>(PDA菜单)实例列表</returns>
        [HttpGet("listNonPage")]
        public async Task<List<WmsPdaPowerOutput>> ListNonPageAsync([FromQuery] WmsPdaPowerSearchNonPage input)
        {
            var pCode = input.Code?.Trim() ?? "";
            var pName = input.Name?.Trim() ?? "";
            var pWorkShopType = input.WorkShopType;
            var wmsPdaPowers = await _wmsPdaPowerRep.DetachedEntities
                .Where(!string.IsNullOrEmpty(pCode), u => EF.Functions.Like(u.Code, $"%{pCode}%")) 
                .Where(!string.IsNullOrEmpty(pName), u => EF.Functions.Like(u.Name, $"%{pName}%")) 
                .Where(pWorkShopType != null, u => u.WorkShopType == pWorkShopType)
            .OrderBy(PageInputOrder.OrderNonPageBuilder(input))
            .ProjectToType<WmsPdaPowerOutput>()
            .ToListAsync();
            return wmsPdaPowers;
        }


        /// <summary>
        /// 增加PDA菜单
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("add")]
        public async Task Add(AddWmsPdaPowerInput input)
        {
            var wmsPdaPower = input.Adapt<WmsPdaPower>();
            await _wmsPdaPowerRep.InsertAsync(wmsPdaPower);
        }

        /// <summary>
        /// 删除PDA菜单
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("delete")]
        public async Task Delete(DeleteWmsPdaPowerInput input)
        {
            var wmsPdaPower = await _wmsPdaPowerRep.FirstOrDefaultAsync(u => u.Id == input.Id);
            await _wmsPdaPowerRep.DeleteAsync(wmsPdaPower);
        }

        /// <summary>
        /// 更新PDA菜单
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("edit")]
        public async Task Update(UpdateWmsPdaPowerInput input)
        {
            var isExist = await _wmsPdaPowerRep.AnyAsync(u => u.Id == input.Id, false);
            if (!isExist) throw Oops.Oh(ErrorCode.D3000);

            var wmsPdaPower = input.Adapt<WmsPdaPower>();
            await _wmsPdaPowerRep.UpdateAsync(wmsPdaPower,ignoreNullValues:true);
        }

        /// <summary>
        /// 获取PDA菜单
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpGet("detail")]
        public async Task<WmsPdaPowerOutput> Get([FromQuery] QueryeWmsPdaPowerInput input)
        {
            return (await _wmsPdaPowerRep.DetachedEntities.FirstOrDefaultAsync(u => u.Id == input.Id)).Adapt<WmsPdaPowerOutput>();
        }

        /// <summary>
        /// 获取PDA菜单列表
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpGet("list")]
        public async Task<List<WmsPdaPowerOutput>> List([FromQuery] WmsPdaPowerInput input)
        {
            return await _wmsPdaPowerRep.DetachedEntities.ProjectToType<WmsPdaPowerOutput>().ToListAsync();
        }    
         /// <summary>
        /// Excel模板导入PDA菜单功能
        /// </summary>
        /// <param name="file">Excel模板文件</param>
        /// <param name="importExcelType">Excel导入方式</param>
        /// <returns>导入的记录数</returns>
        [HttpPost("fromExcel")]
        public async Task<int> FromExcelAsync(IFormFile file, [FromQuery] ImportExcelType importExcelType)
        {
            int size = 200;
            var excelTemplate = await _sysExcelTemplateService.GetByAppNameAndClassNameAndVersionAsync("WmsPdaPower", "v2");
            if (excelTemplate == null) throw Oops.Oh(ErrorCode.Excel002);
            var keys = excelTemplate.UnionUniqueFields.Split(",") ?? Array.Empty<string>();
            for (var i = 0; i < keys.Length; i++) 
            {
                keys[i] = keys[i]?.Trim() ?? string.Empty;
            }
            ExcelUtil.FromExcel(file, excelTemplate.HeadStartLine, excelTemplate.DataStartLine, out List<string> headers, out List<List<object?>> data, out string sheetName);
            List<WmsPdaPowerOutput> wmsPdaPowerList = DataConvertUtil.ToObjectList(headers, data, sheetName, keys, excelTemplate?.DataStartLine ?? 2, out Dictionary<string, WmsPdaPowerOutput> dict);
            List<Dictionary<string, object>> uniqueKeyValueDictList = wmsPdaPowerList.ParseUniqueKeyValueDictList(keys.ToList(), excelTemplate?.DataStartLine ?? 2, sheetName);
            var filters = DataConvertUtil.GetExpressionListByUniqueDict<WmsPdaPower>(keys.ToList(), uniqueKeyValueDictList, size);
            var selectKeys = keys.ToList();
            if(!selectKeys.Contains("Id")) selectKeys.Add("Id");
            var selector = DataConvertUtil.GetSelectExpressionListByUniqueDict<WmsPdaPower, WmsPdaPowerOutput>(selectKeys);
            List<WmsPdaPower> updates = new();
            List<WmsPdaPower> adds = new();

            lock (_lock)
            {
                foreach (var filter in filters)
                {
                    var wmsPdaPowerExistSubList = _wmsPdaPowerRep.Where(filter).Select(selector).ToList();
                    wmsPdaPowerExistSubList.ForEach(x => 
                    {
                        var k = DataConvertUtil.GetKey(x, keys);
                        if (dict.ContainsKey(k)) dict[k].Id = x.Id;
                    });
                }
                foreach (var wmsPdaPower in wmsPdaPowerList) 
                {
                    if (wmsPdaPower.Id > 0)
                    {
                        if (importExcelType == ImportExcelType.ADD_AND_UPDATE) updates.Add(wmsPdaPower.Adapt<WmsPdaPower>());
                    }
                    else 
                    {
                        adds.Add(wmsPdaPower.Adapt<WmsPdaPower>());
                    }
                }

                if (importExcelType == ImportExcelType.ADD_AND_UPDATE) updates.ForEach(x => _wmsPdaPowerRep.Update(x));
                

                var maxId = _wmsPdaPowerRep.DetachedEntities.OrderByDescending(x => x.Id).Select(x => x.Id).FirstOrDefault();
                adds.ForEach(x => x.Id = ++maxId);    
                Db.GetDbContext().Set<WmsPdaPower>().AddRange(adds);  
                Db.GetDbContext().SaveChanges();
               
            }
            await Task.CompletedTask;
            return adds.Count;
        }

        /// <summary>
        /// 根据版本下载PDA菜单的Excel导入模板
        /// </summary>
        /// <param name="version">模板版本</param>
        /// <returns>下载的模板文件</returns>
        [HttpGet("downloadExcelTemplate")]
        public async Task<IActionResult> DownloadExcelTemplate([FromQuery] string version)
        {
            var excelTemplate = await _sysExcelTemplateService.GetByAppNameAndClassNameAndVersionAsync("WmsPdaPower", version);
            if (excelTemplate == null) throw Oops.Oh(ErrorCode.Excel002);
            var path = Path.Combine(@"\", excelTemplate.TemplateFileName);
            Stream ms = FileUtil.Download(path, excelTemplate.TemplateFileName);
            var fileName = HttpUtility.UrlEncode($"{excelTemplate.Name}导入模板.xlsx", Encoding.GetEncoding("UTF-8"));
            return new FileStreamResult(ms, "application/octet-stream") { FileDownloadName = fileName };
        }
        /// <summary>
        /// 根据PDA菜单查询参数导出Excel
        /// </summary>
        /// <param name="input">PDA菜单查询参数</param>
        /// <returns>导出的Excel文件</returns>
        [HttpGet("toExcel")]
        public async Task<IActionResult> ToExcelAsync([FromQuery] WmsPdaPowerSearchNonPage input)
        {
            var wmsPdaPowerList = await ListNonPageAsync(input);
            MemoryStream ms = new();
            DataConvertUtil.ToExcelData(wmsPdaPowerList, _sysDictTypeRep, _sysDictDataRep, out List<string> headers, 
                out List<List<object>> data, out string sheetName);
            var excelTemplate = await _sysExcelTemplateService.GetByAppNameAndClassNameAndVersionAsync("WmsPdaPower", "v1");
            if (excelTemplate != null)
            {
                ExcelUtil.ToExcel(excelTemplate.TemplateFileName, headers, data, sheetName, excelTemplate.HeadStartLine, excelTemplate.DataStartLine, ms);
            }
            else 
            {
                ExcelUtil.ToExcel(headers, data, sheetName, ms);
            }
            ms.Position = 0;
            var fileName = HttpUtility.UrlEncode($"{sheetName}[{DateTimeOffset.Now:yyyy-MM-dd}].xlsx", Encoding.GetEncoding("UTF-8"));
            return new FileStreamResult(ms, "application/octet-stream") { FileDownloadName = fileName };
        }
    }
}
